<template>
  <div class="detail">
    <el-card shadow="hover">
      <div slot="header">
        <span>{{ id ? "编辑" : "新增" }}文章</span>
      </div>
      <el-form
        ref="form"
        :model="articleInfo"
        :rules="formRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="7">
            <el-form-item label="作者:" prop="author">
              <el-input
                v-model="articleInfo.author"
                placeholder="作者姓名"
              /> </el-form-item></el-col>
          <el-col :span="7">
            <el-form-item label="标题:" prop="title">
              <el-input
                v-model="articleInfo.title"
                placeholder="文章标题"
              /> </el-form-item></el-col>
          <el-col :span="7">
            <el-form-item label="是否显示:" prop="isShow">
              <el-switch
                v-model="articleInfo.isShow"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="15">
            <el-form-item label="摘要:" prop="summary">
              <el-input
                v-model="articleInfo.summary"
                type="textarea"
                placeholder="摘要"
                :autosize="{ minRows: 4, maxRows: 8 }"
              /> </el-form-item></el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="封面图片:">
              <el-upload
                ref="uploadCoverImg"
                action="http://leju.bufan.cloud/lejuAdmin/material/uploadFileOss"
                :headers="token"
                :on-success="handleUploadSuccess"
                :before-upload="handleBeforeUpload"
                accept=".png,.jpeg,.gif,.jpg,.webp"
              >
                <img
                  v-if="articleInfo.coverImg"
                  :src="articleInfo.coverImg"
                  class="cover-img"
                >
                <el-button
                  v-else
                  size="mini"
                  type="primary"
                >上传图片</el-button>

                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="编辑器类型:" size="normal">
              <el-radio-group
                v-model="articleInfo.editorType"
                @change="handlerEditorTypeChange"
              >
                <el-radio :label="0"> 富文本 </el-radio>
                <el-radio :label="1"> Markdown </el-radio>
              </el-radio-group>
              <i
                class="el-icon-warning tips"
                style="color: #e6a23c"
              >&nbsp;&nbsp;注意!切换编辑器会清空编辑内容</i>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24" :offset="0">
            <el-form-item label="">
              <div v-if="articleInfo.editorType == 0">
                <Tinymce v-model="articleInfo.content1" />
              </div>
              <div v-else>
                <mavon-editor
                  ref="markdownEdit"
                  v-model="articleInfo.content1"
                  @imgAdd="$imgAdd"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="footer">
          <el-form-item>
            <el-button type="primary" @click="onSubmit">{{
              id ? "保存更改" : "立即创建"
            }}</el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-card>
  </div>
</template>
<script>
import Tinymce from '@/components/Tinymce'
import axios from 'axios'
import { getToken } from '@/utils/auth'
import {
  addArticle,
  productArticle,
  updateArticle
} from '@/api/content/articleList/index'

export default {
  components: {
    Tinymce
  },
  data() {
    return {
      id: '',
      articleInfo: {
        author: '',
        title: '',
        coverImg: '',
        editorType: 0,
        isShow: 1,
        content1: ''
      }, // 文章信息,
      formRules: {
        author: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }]
      }
    }
  },
  computed: {
    token() {
      return { token: getToken() }
    }
  },

  created() {
    this.id = this.$route.query.id
    if (this.id) {
      // 如果存在id就是编辑页,否则是新增页
      this.getArticleInfo()
    }
  },
  methods: {
    // 获取文章详情
    async getArticleInfo() {
      const { success, data, message } = await productArticle(this.id)
      if (success) {
        this.articleInfo = data.productArticle
      } else {
        this.$message.error(message)
      }
    },
    // 上传文件之前,检查文件是否过大
    handleBeforeUpload(file) {
      var imgReg = /^image\/(jpeg|jpg|png|gif|webp)$/
      const isImg = imgReg.test(file.type)
      const isLt1Dot5M = 1.5 * 1024 * 1024 > file.size
      if (!isImg) {
        this.$message.error('上传头像图片只能是 jpeg|jpg|png|gif|webp 格式!')
      }
      if (!isLt1Dot5M) {
        this.$message.error('上传头像图片大小不能超过 1.5MB!!!')
      }
      return isLt1Dot5M && isImg
    },
    // 上传图片成功
    handleUploadSuccess(res) {
      this.articleInfo.coverImg = res.data.fileUrl
      // 上传成功后, 情况上传列表
      this.$refs.uploadCoverImg.clearFiles()
    },
    // form提交
    onSubmit() {
      console.log('onSubmit..', this.articleInfo)
      this.$refs.form.validate((valid) => {
        // 表单校验通过
        if (valid) {
          if (!this.articleInfo.content1) {
            this.$message.error('文本内容不能为空')
            return
          }
          if (this.articleInfo.editorType === 0) {
            this.articleInfo.content2 = this.articleInfo.content1
          } else {
            // 如果是markDown, 需要获取d_render
            this.articleInfo.content2 = this.$refs.markdownEdit.d_render
          }
          let ajaxApi
          if (this.id) {
            ajaxApi = updateArticle
          } else {
            ajaxApi = addArticle
          }

          ajaxApi(this.articleInfo).then((res) => {
            const { success, message } = res
            if (success) {
              this.$message.success('保存成功')
              // 跳转到列表页
              this.$router.push('/content/articleList')
            } else {
              this.$message.error(message)
            }
          })
        }
      })
    },
    // 绑定@imgAdd event
    $imgAdd(pos, $file) {
      // 第一步.将图片上传到服务器.
      var formdata = new FormData()
      formdata.append('file', $file)
      axios({
        url: 'http://leju.bufan.cloud/lejuAdmin/material/uploadFileOss',
        method: 'post',
        data: formdata,
        headers: { 'Content-Type': 'multipart/form-data', token: getToken() }
      }).then((res) => {
        // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
        /**
         * $vm 指为mavonEditor实例，可以通过如下两种方式获取
         * 1. 通过引入对象获取: `import {mavonEditor} from ...` 等方式引入后，`$vm`为`mavonEditor`
         * 2. 通过$refs获取: html声明ref : `<mavon-editor ref=md ></mavon-editor>，`$vm`为 `this.$refs.md`
         */
        const { success, data, message } = res.data
        if (success) {
          this.$refs.markdownEdit.$img2Url(pos, data.fileUrl)
        } else {
          this.$message.error(message)
        }
      })
    },
    // 监听编辑器变动
    handlerEditorTypeChange() {
      this.$nextTick(() => {
        this.articleInfo.content1 = ''
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.detail {
  margin: 30px;
  .cover-img {
    width: 100px;
    height: 100px;
  }
  .tips {
    margin-left: 20px;
  }
  .footer {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
